package com.taotao.tools.validate.validator;

import com.taotao.tools.core.reflect.ReflectUtils;
import com.taotao.tools.core.str.StringUtil;
import com.taotao.tools.core.str.format.MessageFormatUtil;
import com.taotao.tools.validate.annotations.MustEquals;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;


@Slf4j
public class MustEqualsValidator implements ConstraintValidator<MustEquals, Object> {

    private MustEquals anno;

    @Override
    public void initialize(MustEquals anno) {
        this.anno = anno;
    }


    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context) {

        try {
            Object val1 = ReflectUtils.getFieldValue(obj, anno.fieldName1());
            Object val2 = ReflectUtils.getFieldValue(obj, anno.fieldName2());

            if (Objects.equals(val1, val2)) {
                if (StringUtil.isBlank(anno.message())) {
                    //重写错误提示
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate(MessageFormatUtil.format("字段{}与字段{}不相等", anno.fieldName1(), anno.fieldName2())).addConstraintViolation();
                }
                return false;
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }


        return true;
    }


}
